package com.zzyl.intercept;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.zzyl.constant.Constants;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.properties.JwtProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.UserThreadLocal;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class UserInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 如果不是映射到方法就放行，比如跨域验证请求、静态资源等不需要身份校验的请求： 只兰姐Controller类的方法
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        // 2、 获取请求头的令牌
        String token = request.getHeader(Constants.USER_TOKEN);
        if (StrUtil.isEmpty(token)) {
            // 没有令牌或令牌失效
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }

        // 3、校验令牌
        Claims claims = JwtUtil.parseJWT(jwtProperties.getBase64EncodedSecretKey(), token);
        //判断claims是否为空
        if (ObjectUtil.isEmpty(claims)){
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }
//        Long userId = (long) claims.get(Constants.JWT_USERID);
//
//        if (userId == null) {
//            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
//        }

        Long userId = MapUtil.get(claims, Constants.JWT_USERID, Long.class);
        if(ObjectUtil.isEmpty(userId)){
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }


        // 4、通过则放行
        // TODO

        UserThreadLocal.set(userId);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserThreadLocal.remove();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
